using Cinemachine;
using Tools;
using UnityEngine;

public class PlayerCameraScaler : VirtualCameraController
{
    private PlayerEntity playerEntity;
    private MoveAlongPathComponent moveAlongPathComponent;

    [SerializeField]
    [Range(0f, 20f)]
    private float defaultScaleSpeed = 5f;
    [SerializeField]
    private float defaultFOV = 60f;
    [SerializeField]
    private float focusFOV = 50f;

    private float targetFOV;

    protected override void Awake()
    {
        base.Awake();
        playerEntity = PlayerEntity.Instance;
        moveAlongPathComponent = playerEntity.MoveAlongPathComponent;
        targetFOV = defaultFOV;
    }

    private void FixedUpdate()
    {
        targetFOV = moveAlongPathComponent.timer.Current switch
        {
            <=5f => defaultFOV,
            >5f => focusFOV,
            _ => targetFOV,
        };
        float current = cvm.m_Lens.FieldOfView;
        float delta = targetFOV - current;
        float speed = CalculateScaleSpeed(delta);
        float deltaFOV = Mathf.Sign(delta) * Time.fixedDeltaTime * speed;
        if (Mathf.Abs(deltaFOV) > Mathf.Abs(delta))
            deltaFOV = delta;

        cvm.m_Lens.FieldOfView = current + deltaFOV;
    }

    private float CalculateScaleSpeed(float delta)
    {
        float ik = Mathf.Abs(delta / (defaultFOV - focusFOV));
        float k = MathTool.PLerp(0.1f, 1f, ik, 2f);
        return k * defaultScaleSpeed;
    }

    private void OnDrawGizmos()
    {
        if(!Application.isPlaying)
        {
            GetComponentInChildren<CinemachineVirtualCamera>().m_Lens.FieldOfView = defaultFOV;
        }
    }
}
